//
//  HTHomeScreen.swift
//  MagaCore
//
//  Created by MrMessy on 2023/4/29.
//

import AppLovinSDK
import Refresh
import SwiftUI

struct HTHomeScreen: View {
    @Environment(\.scenePhase) var scenePhase
    @EnvironmentObject private var var_store: HTAppStore
    @State private var var_purchasingSubscribe: Bool = false
    @State private var var_curSubscribe: HTSubscribe?
    @State private var var_popularIndex: Int = 0
    @State private var var_showMRECAdView: Bool = true
    @State private var var_recentPlayFirst: HTAnime?
    @State private var var_closeInterstitialTime: Date = Date()
    @State private var var_showInterstitialAd: Bool = false
    @State private var var_showRewardedAd: Bool = false
    @State private var var_navigate = false
    @State private var var_id: String = ""
    @State private var var_epId: String = ""
    @State private var var_showPushToRecentPlay: Bool = false
    @State private var var_showEpisodesPopupView: Bool = false
    // 广告
    @State private var var_interstitialAd: MAInterstitialAd!
    @State private var var_rewardedAd: MARewardedAd!

    @State private var var_headerRefreshing: Bool = false
    @State private var var_subjects: [HTSubject] = []

    @State private var var_showAlert: Bool = false
    var body: some View {
        ZStack {
            // 跳转播放
            NavigationLink(destination: HTRecentPlayScreen(), isActive: $var_showPushToRecentPlay) {
                EmptyView()
            }
            // 加载广告
            HTInterstitialAd(var_didLoad: { interstitialAd in
                var_interstitialAd = interstitialAd
            }, var_didHide: {
                ht_hideInterstitialAd()
            })

            // 展示广告
            HTRewardedAd(var_didLoad: { rewardedAd in
                var_rewardedAd = rewardedAd
            }, var_didHide: {
                // 隐藏
                ht_hideRewardedAd()
            })

            // 背景图
            VStack {
                Image("home_mask1")
                    .resizable()
                    .frame(width: UIScreen.main.bounds.width, height: UIDevice.ht_fixToWidth(width: 116))
                Image("home_mask2")
                    .resizable()
                    .frame(width: UIScreen.main.bounds.width, height: UIDevice.ht_fixToWidth(width: 154))
                    .offset(y: -10)
            }
            .frame(maxHeight: .infinity, alignment: .top)

            VStack {
                HTNavigationBar {
                    ScrollView(showsIndicators: false) {
                        // 下拉刷新
                        RefreshHeader(refreshing: $var_headerRefreshing, action: {
                            ht_loadData(isPull: true)
                        }) { _ in
                            HTActivityIndicator(var_style: .medium)
                        }

                        VStack(spacing: 30) {
                            ForEach(0 ..< var_subjects.count, id: \.self) { index in
                                let var_subject = var_subjects[index]
                                if index == 0 {
                                    // 轮播图
                                    HTBannerView(var_banners: var_subject.ht_Animes()!)
                                }

                                if (var_subject.var_data_type == "103" || var_subject.var_data_type == "1") && index != 0 {
                                    HTSubjectScrollView(var_subject: var_subject)
                                    if index == 1 || index % 3 == 1 && var_showMRECAdView && var_curSubscribe == nil {
                                        HTMRECAdView(var_onDisappear: {
                                            var_showMRECAdView = false
                                        })
                                    }
                                }
                                if index == 1 {
                                    HTSpecialOfferForYou()
                                }
                            }
                        }
                        .padding(.vertical, 30)
                        .padding(.bottom, UIDevice.ht_tabBarFullHeight())
                    }
                    .enableRefresh()
                    .frame(minWidth: UIDevice.ht_screenWidth())
                }
                .ht_backButtonHidden(true)
                .ht_background(Color.clear)
                .ht_navigationBarTitleView(titleView: {
                    HTHomeSearch(var_popular: (var_store.state.var_searchState.var_populars ?? []).count > 0 ? (var_store.state.var_searchState.var_populars ?? [])[var_popularIndex] : HTSearchPopular())
                })
                .ht_navigationBarItems(leading: {
                    HTShareButton(var_onShare: {
                        HTNetworkManager().ht_requestForBuried(.htEnumMomeMClNew(var_kid: "2"))
                    })
                }, trailing: {
                    Button {
                        var_showPushToRecentPlay = true
                        HTNetworkManager().ht_requestForBuried(.htEnumMomeMClNew(var_kid: "3"))
                    } label: {
                        Image("record")
                            .resizable()
                            .frame(width: 24, height: 24)
                    }
                })
            }
            // 最近播放
//                  if (var_recentPlayFirst != nil) {
//                    HTEpisodesPopupView(var_showEpisodesPopupView: $var_showEpisodesPopupView, var_showInterstitialAd: $var_showInterstitialAd, var_recentPlayFirst: var_recentPlayFirst!)
//                  }

            /// 视频播放详情页
            //      NavigationLink(destination: HTVideoDetailScreen(var_id: var_id, var_source: "8"), isActive: $var_navigate ) {
            //        EmptyView()
            //      }
            if var_showAlert {
                HTRecentAlertScreen()
                    .offset(CGSizeMake(0, 300))
            }
        }
        .frame(maxHeight: .infinity, alignment: .top)
        .background(Color(hex: "#f5f5f5"))
        .ignoresSafeArea()
        .onReceive(NotificationCenter.default.publisher(for: HTConfig.STATIC_notification_showEpisodesPopupView), perform: { notification in
            // 监听是否弹出播放历史
            if let userInfo = notification.userInfo {
                let value = userInfo["status"] as! String
                if value == "show" {
                    var_showEpisodesPopupView = true
                } else if value == "hide" {
                    var_showEpisodesPopupView = false
                }
            }
        })
        .onReceive(NotificationCenter.default.publisher(for: HTConfig.STATIC_notification_showRecentAlert), perform: { notification in
            /** 显示历史播放 */
            if let userInfo = notification.userInfo {
                let value = userInfo["status"] as! String
                if value == "canshow" {
                    var_showAlert = true
                }
            }
        })
        // 插屏广告播放
        .onReceive(NotificationCenter.default.publisher(for: HTConfig.STATIC_notification_interstitialAd), perform: { notification in
            if let userInfo = notification.userInfo {
                let value = userInfo["status"] as! String
                if value == "canshow" {
                    ht_showInterstitialAd()
                }
            }
        })
        // 激励视频播放
        .onReceive(NotificationCenter.default.publisher(for: HTConfig.STATIC_notification_rewardedAd), perform: { _ in
            #warning("暂时注释")
//            if let userInfo = notification.userInfo {
//                let value = userInfo["status"] as! String
//                if (value == "canshow") {
//                    ht_showRewardedAd()
//                }
//            }
        })
        .onAppear {
            let var_populars = var_store.state.var_searchState.var_populars ?? []
            if var_popularIndex == var_populars.count - 1 {
                var_popularIndex = 0
            } else {
                var_popularIndex += 1
            }
            if var_store.state.var_shareState.var_share == nil {
                var_store.dispatch(HTEnumShareAction.ht_shareConfig(var_p1: "", var_p2: "0"))
            }
            if var_recentPlayFirst == nil {
                var_store.dispatch(HTEnumAnimeAction.ht_recentPlayList(callback: { animes in
                    if animes!.count > 0 {
                        var_recentPlayFirst = animes!.first
                    }
                }))
            }
            var_curSubscribe = var_store.state.var_subscribeState.var_curSubscribe ?? nil
            var_store.dispatch(HTEnumSearchAction.ht_populars(callback: nil))
            if var_subjects.count == 0 {
                ht_loadData()
            }
        }
        .onDisappear {
            var_showInterstitialAd = false
        }
        .onReceive(var_store.objectWillChange) { _ in
            var_curSubscribe = var_store.state.var_subscribeState.var_curSubscribe ?? nil
            var_purchasingSubscribe = var_store.state.var_subscribeState.var_purchasingSubscribe ?? false
            let var_push = var_store.state.var_pushState.var_push
            if var_push != nil {
                if var_push?.var_flag == "19" || var_push?.var_flag == "20" {
                    var_id = var_push?.var_TTid ?? ""
                    var_epId = var_push?.var_eps_id ?? ""
                } else if var_push?.var_flag == "17" {
                    var_id = var_push?.var_mid ?? ""
                }
                var_navigate = true
                var_store.dispatch(HTEnumPushAction.ht_pageToPlayScreen(var_push: nil))
            }
        }
        .onChange(of: scenePhase) { newScenePhase in
            switch newScenePhase {
            case .active:
                print("应用启动了")
                var timeInterval = var_closeInterstitialTime.timeIntervalSinceNow
                timeInterval = -timeInterval
                if var_store.state.var_adState.var_adConfig?.var_inter_screen_ad_secs != nil && timeInterval > Double(var_store.state.var_adState.var_adConfig?.var_inter_screen_ad_secs ?? 0) {
                    if var_curSubscribe == nil && !var_purchasingSubscribe {
                        ht_showInterstitialAd()
                    } else {
                        NotificationCenter.default.post(name: HTConfig.STATIC_notification_sceneActive, object: nil, userInfo: ["status": "active"])
                    }
                } else {
                    NotificationCenter.default.post(name: HTConfig.STATIC_notification_sceneActive, object: nil, userInfo: ["status": "active"])
                }
            case .inactive:
                print("应用休眠了")
            case .background:
                print("应用在后台展示")
            @unknown default:
                print("default")
            }
        }
    }

    /// <#Description#>
    /// - Parameter isPull: <#isPull description#>
    private func ht_loadData(isPull: Bool = false) {
        var_store.dispatch(HTEnumAnimeAction.ht_recentPlayList(callback: { animes in
            var_headerRefreshing = false
            var_showMRECAdView = true
            if animes!.count > 0 {
                var_store.dispatch(HTEnumAnimeAction.ht_homeData(id: animes!.first?.var_id, andCallback: { var_result in
                    var_subjects = var_result!
                }))
            } else {
                var_store.dispatch(HTEnumAnimeAction.ht_homeData(id: "", andCallback: { var_result in
                    var_subjects = var_result!
                }))
            }
        }))
    }

    private func ht_showInterstitialAd() {
        if var_showRewardedAd {
            return
        }

        if var_interstitialAd != nil && var_interstitialAd.isReady {
            NotificationCenter.default.post(name: HTConfig.STATIC_notification_interstitialAd, object: nil, userInfo: ["status": "show"])
            var_showInterstitialAd = true
            // 展示广告
            //      var_interstitialAd.show()
        }
    }

    private func ht_hideInterstitialAd() {
        NotificationCenter.default.post(name: HTConfig.STATIC_notification_interstitialAd, object: nil, userInfo: ["status": "hide"])
        var_showInterstitialAd = false
        var_closeInterstitialTime = Date()
        if var_interstitialAd != nil {
            var_interstitialAd.load()
        }
    }

    private func ht_showRewardedAd() {
        if var_showInterstitialAd {
            return
        }

        if var_rewardedAd != nil && var_rewardedAd.isReady {
            NotificationCenter.default.post(name: HTConfig.STATIC_notification_rewardedAd, object: nil, userInfo: ["status": "show"])
            var_showRewardedAd = true
            var_rewardedAd.show()
        }
    }

    private func ht_hideRewardedAd() {
        NotificationCenter.default.post(name: HTConfig.STATIC_notification_rewardedAd, object: nil, userInfo: ["status": "hide"])
        var_showRewardedAd = false
        if var_rewardedAd != nil {
            var_rewardedAd.load()
        }
    }
}
